<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="mini" :inline="true" v-show="showSearch">

      <!--算法名称搜索
      <el-form-item  prop="algorithm">
        <el-input
          v-model="queryParams.algorithm"
          placeholder="Pls input Algorithm Name"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>-->

      <!--选择大语言模型-->
      <el-form-item prop="llm">
        <el-select v-model="queryParams.llm" placeholder="Select LLM" clearable>
          <el-option v-for="dict in dict.type.llm_model" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <!--选择Prompt-->
      <el-form-item prop="promptId">
        <el-select v-model="queryParams.promptId" placeholder="Select Prompt" clearable>
          <el-option v-for="dict in prompts" :key="dict.identifier" :label="dict.identifier" :value="dict.id" />
        </el-select>
      </el-form-item>

      <!--请选择ADE知识库-->
      <el-form-item prop="adekbId">
        <el-select v-model="queryParams.adekbId" placeholder="Select ADE KB" clearable>
          <el-option v-for="dict in adekbs" :key="dict.id" :label="dict.name" :value="dict.id" />
        </el-select>
      </el-form-item>

      <!--Select LLM Lab Status-->
      <el-form-item prop="status">
        <el-select v-model="queryParams.status" placeholder="Select Status" clearable>
          <el-option v-for="dict in dict.type.lab_status" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>

      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">Search</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">Reset</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
          v-hasPermi="['ade:raglab:add']">New</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="raglabList">
      <el-table-column label="ID" align="center" width="60" prop="id" />
      <el-table-column label="Name" align="left" width="100" prop="algorithm" show-overflow-tooltip />
      <el-table-column label="LLM" align="center" width="100" prop="llm">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.llm_model" :value="scope.row.llm" />
        </template>
      </el-table-column>
      <el-table-column label="Prompt" width="120" align="left" prop="promptId" :formatter="formatPromptName"
        show-overflow-tooltip />

      <el-table-column label="ADE KB" align="center" prop="adekbId" :formatter="formatAdekbName" show-overflow-tooltip>
      </el-table-column>

      <!--
      <el-table-column label="SimScore" align="center" prop="simScore" />
      <el-table-column label="TopN" align="center" prop="topn" />
      -->

      <!--执行进度 完成数/总数量 -->
      <el-table-column label="Progress" width="120" align="center">
        <template slot-scope="scope">
          {{ scope.row.finished || 0 }} / {{ scope.row.total || 0 }}
        </template>
      </el-table-column>

      <!--Status 状态-->
      <el-table-column label="Status" width="90" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.lab_status" :value="scope.row.status" />
        </template>
      </el-table-column>

      <!--命中知识库的记录数-->
      <el-table-column label="Hits" align="center" prop="hitStandard" />
      <el-table-column label="Knowledges" align="center">
        <template slot-scope="scope">
          {{ formatToThreeDecimals(scope.row.hitKnowledgeCount / scope.row.hitStandard) }}
        </template>
      </el-table-column>

      <el-table-column label="SimScore" align="center">
        <template slot-scope="scope">
          {{ formatToThreeDecimals(scope.row.hitSimscoreTotal / scope.row.hitKnowledgeCount) }}
        </template>
      </el-table-column>


      <!--precision-->
      <el-table-column label="Precision" width="120" align="center" prop="precisionMean">
        <template slot-scope="scope">
          <div
            v-html="formatToFourDecimals(scope.row.precisionMean) + ' ± ' + formatToFourDecimals(scope.row.precisonSd)" />
        </template>
      </el-table-column>
      <!--recall-->
      <el-table-column label="Recall" width="120" align="center" prop="recallMean">
        <template slot-scope="scope">
          <div v-html="formatToFourDecimals(scope.row.recallMean) + ' ± ' + formatToFourDecimals(scope.row.recallSd)" />
        </template>
      </el-table-column>
      <!--f1-->
      <el-table-column label="F1-Score" width="120" align="center" prop="f1Mean">
        <template slot-scope="scope">
          <div v-html="formatToFourDecimals(scope.row.f1Mean) + ' ± ' + formatToFourDecimals(scope.row.f1Sd)" />
        </template>
      </el-table-column>

      <!--
      <el-table-column label="Hit Adeknowledges" align="center" prop="hitKnowledgeCount" />
      <el-table-column label="Hit Total SimScore" align="center" prop="hitSimscoreTotal" />
       <el-table-column label="Remark" align="center" prop="remark" />
      <el-table-column label="Other Metrics" align="center" prop="props" />
      -->

      <el-table-column label="Actions" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status === 'running' || scope.row.status === 'failed' || scope.row.status === 'success'"
            size="mini" type="text" icon="el-icon-view" @click="handleDetail(scope.row)"></el-button>
          <el-button v-if="scope.row.status === 'ready'" size="mini" type="text" icon="el-icon-edit"
            @click="handleUpdate(scope.row)" v-hasPermi="['ade:raglab:edit']"></el-button>
          <el-button v-if="scope.row.status === 'ready' || scope.row.status === 'failed'" size="mini" type="text"
            icon="el-icon-position" @click="handleExecute(scope.row)" v-hasPermi="['ade:llmlab:edit']"></el-button>
          <el-button
            v-if="scope.row.status === 'failed' || scope.row.status === 'success' || scope.row.status === 'ready'"
            size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
            v-hasPermi="['ade:raglab:remove']"></el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />

    <!-- 添加或修改Ade Rag Lab对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px" size="mini">

        <!--输入实验名称 以及 选择大语言模型-->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="Name" prop="algorithm">
              <el-input v-model="form.algorithm" placeholder="Input Algorithm Name" style="width: 250px;" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="LLM" prop="llm">
              <el-select v-model="form.llm" placeholder="Select LLM" style="width: 250px;">
                <el-option v-for="dict in dict.type.llm_model" :key="dict.value" :label="dict.label"
                  :value="dict.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <!--选择提示词 -->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="Prompt" prop="promptId">
              <el-select v-model="form.promptId" placeholder="Select Prompt" clearable style="width: 250px;">
                <el-option v-for="dict in prompts" :key="dict.identifier" :label="dict.identifier" :value="dict.id" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="ADE KB" prop="adekbId">
              <el-select v-model="form.adekbId" placeholder="Select ADE KB" clearable style="width: 250px;">
                <el-option v-for="dict in adekbs" :key="dict.id" :label="dict.name" :value="dict.id" />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>


        <!--选择simscore 以及 topN-->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="SimScore" prop="simScore">
              <el-input-number v-model="form.simScore" placeholder="Input SimScore" style="width: 250px;" :min="0.1"
                :max="1" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="TopN" prop="topn">
              <el-input-number v-model="form.topn" placeholder="Input TopN" style="width: 250px;" :min="3" :max="10" />
            </el-form-item>
          </el-col>
        </el-row>


        <!--选择chuNktpe  同时 选择分析的标准数据集数量-->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="Chunk Type" prop="chunkType">
              <el-select v-model="form.chunkType" placeholder="Select Chunk Type" size="mini" clearable
                style="width: 250px;">
                <el-option v-for="dict in dict.type.chunk_type" :key="dict.value" :label="dict.label"
                  :value="dict.value" />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="Standards" prop="standardSize">
              <el-input-number v-model="form.total" placeholder="Input Standard Dataset Size" style="width: 250px;"
                :min="100" :max="3000" />
            </el-form-item>
          </el-col>
        </el-row>

        <!--输入folds 以及 fold_size-->
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="Folds" prop="folds">
              <el-input-number v-model="form.folds" placeholder="Input Folds" style="width: 250px;" :min="1"
                :max="10" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="Fold Size" prop="foldSize">
              <el-input-number v-model="form.foldSize" placeholder="Input Fold Size" style="width: 250px;" :min="100"
                :max="1000" />
            </el-form-item>
          </el-col>
        </el-row>


        <el-form-item label="Remark" prop="remark">
          <el-input v-model="form.remark" placeholder="Input Remark" type="textarea" :rows="3" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">Confirm</el-button>
        <el-button @click="cancel">Cancel</el-button>
      </div>
    </el-dialog>

    <!--RAG Lab Detail-->
    <el-dialog :visible.sync="showDialog" @close="handClose()" width="80%" :title="detailTitle">
      <aderagb-detail-dialog v-if="selectedId" :id="selectedId" />
    </el-dialog>
  </div>
</template>

<script>
import { listRaglab, getRaglab, delRaglab, addRaglab, updateRaglab, executeRagLab } from "@/api/ade/raglab";
import { listAllPrompt } from "@/api/ade/prompt";
import { listAllAdebase } from "@/api/ade/adebase";

import AderagbDetailDialog from "@/views/ade/raglab/detail.vue";

export default {
  name: "Raglab",
  dicts: ['prompt_type', 'llm_model', 'lab_status', 'chunk_type'],
  components: {
    AderagbDetailDialog,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // Ade Rag Lab表格数据
      raglabList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        algorithm: null,
        llm: null,
        promptId: null,
        adekbId: null,
        simScore: null,
        topn: 5,
        pos: null,
        neg: null,
        status: null,
        folds: null,
        foldSize: null,
        hitStandard: null,
        finished: null,
        total: null,
        precisionMean: null,
        precisonSd: null,
        recallMean: null,
        recallSd: null,
        f1Mean: null,
        f1Sd: null,
        hitKnowledgeCount: null,
        hitSimscoreTotal: null,
        props: null,
      },
      // 表单参数
      form: {
        simScore: 0.6,
        topn: 5,
        total: 1000,
        status: 'ready',
        folds: 10,
        foldSize: 800,
      },
      // 表单校验
      rules: {
        algorithm: [
          { required: true, message: "Algorithm Name can not be empty!", trigger: "blur" }
        ],
        llm: [
          { required: true, message: "LLM can not be empty!", trigger: "change" }
        ],
        promptId: [
          { required: true, message: "Prompt can not be empty!", trigger: "change" }
        ],
        adekbId: [
          { required: true, message: "ADE KB can not be empty!", trigger: "change" }
        ],
        simScore: [
          { required: true, message: "SimScore can not be empty!", trigger: "blur" }
        ],
        topn: [
          { required: true, message: "TopN can not be empty!", trigger: "blur" }
        ],
        chunkType: [
          { required: true, message: "Chunk Type can not be empty!", trigger: "change" }
        ],
        folds: [
          { required: true, message: "Folds can not be empty!", trigger: "blur" }
        ],
        foldSize: [
          { required: true, message: "Fold Size can not be empty!", trigger: "blur" }
        ],
      },
      // Prompt
      prompts: [],
      promptList: {}, //缓存的prompt对象
      adekbs: [], //ADE知识库列表

      // 弹出层是否显示
      showDialog: false,
      // 选中的ID
      selectedId: null,
      // 详情对话框标题
      detailTitle: "",
    };
  },
  created() {
    this.getList();
    this.getPromptList();
    this.getAdekbList();
  },
  methods: {
     //关闭详情对话框
    handClose() {
      this.showDialog = false;
      this.selectedId = null;
    },
    //跳转到详情页面
    handleDetail(row) {
      this.detailTitle = 'ADE Rag LAB-[' + row.algorithm + "] Detail";
      this.selectedId = row.id;
      this.showDialog = true;
    },
    //执行rag实验
    handleExecute(row) {
      const id = row.id || this.ids;
      this.$modal.confirm('Are you sure to execute Ade Rag Lab:"' + id + '"').then(() => {
        return executeRagLab(id);
      }).then(() => {
        this.$modal.msgSuccess("Execution started successfully");
        this.getList();
      }).catch(() => { });
    },
    //获取知识库名称
    formatAdekbName(row, column, cellValue) {
      const adekb = this.adekbs.find(adekb => adekb.id === cellValue);
      return adekb ? adekb.name : cellValue; // 如果找到ADE KB对象，则返回名称

    },
    //获取所有的知识库列表
    getAdekbList() {
      listAllAdebase().then(response => {
        this.adekbs = response.data;
      }).catch(() => {
        this.$message.error("Error occurred while fetching ADE Knowledge Base!");
      });
    },
    //获取Prompt名称
    formatPromptName(row, column, cellValue) {
      console.log("formatPromptName called with cellValue:", cellValue);
      const prompt = this.promptList[cellValue];
      return prompt ? prompt.identifier : cellValue; // 如果缓存中有Prompt对象，则返回
    },
    /** 获取Prompt列表 */
    getPromptList() {
      var data = { "type": 'RAG' };
      listAllPrompt(data)
        .then((response) => {
          var list = response.data;
          this.prompts = list;
          this.promptList = {}; // 初始化缓存对象
          for (let i = 0; i < list.length; i++) {
            this.promptList[list[i].id] = list[i]; // 缓存Prompt对象
          }
        })
        .catch((error) => {
          this.$message.error("Error fetching prompts:", error);
        });
    },
    /** 查询Ade Rag Lab列表 */
    getList() {
      this.loading = true;
      listRaglab(this.queryParams).then(response => {
        this.raglabList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    formatToFourDecimals(value) {
      if (!isNaN(value)) {
        const formattedValue = Number(value).toFixed(4);
        if (value >= 0.9) {
          return `<span style="color: green;font-weight:800">${formattedValue}</span>`;
        } else if (value >= 0.8) {
          return `<span style="color: orange;font-weight:800">${formattedValue}</span>`;
        }
        return formattedValue;
      }
      return value; // 如果不是数字，直接返回原值
    },
    formatToThreeDecimals(value) {
      if (!isNaN(value)) {
        const formattedValue = Number(value).toFixed(4);
        return formattedValue;
      }
      return value; // 如果不是数字，直接返回原值
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        simScore: 0.5,
        topn: 5,
        total: 1000,
        status: 'ready',
        folds: 10,
        foldSize: 800,
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加Ade Rag Lab";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getRaglab(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改Ade Rag Lab";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateRaglab(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addRaglab(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除Ade Rag Lab编号为"' + ids + '"的数据项？').then(function () {
        return delRaglab(ids);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => { });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('ade/raglab/export', {
        ...this.queryParams
      }, `raglab_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
